import requests

from config import host
from utils.get_log import GetLog

logger=GetLog.get_logger()
class Api:
    # 初始化，获取请求方法、url、请求头、请求数据

    def __init__(self, case):
        self.method = case.get("method")
        self.url = host + case.get("path")
        self.headers = case.get("headers")
        self.params = case.get("params")

    # 封装 get 请求
    def _get(self):
        logger.info("正在调用 get 请求方法")
        return requests.get(url=self.url, params=self.params, headers=self.headers)

    # 封装 post 请求
    def _post(self):
        logger.info("正在调用 post 请求方法")
        # 判断请求参数类型：json/data
        if self.headers.get("Content-Type") == "application/json":
            return requests.post(url=self.url, json=self.params, headers=self.headers)
        elif self.headers.get("Content-Type") == "application/x-www-form-urlencoded":
            return requests.post(url=self.url, data=self.params, headers=self.headers)

    # 封装 put 请求
    def _put(self):
        logger.info("正在调用 put 请求方法")
        return requests.put(url=self.url, json=self.params, headers=self.headers)

    # 封装 delete 请求
    def _delete(self):
        logger.info("正在调用 delete 请求方法")
        return requests.delete(url=self.url, params=self.params, headers=self.headers)

    # 调用 请求方法
    def run_method(self):
        logger.info("正在调用接口请求方法")
        if self.method == "get":
            return self._get()
        elif self.method == "post":
            return self._post()
        elif self.method == "put":
            return self._put()
        elif self.method == "delete":
            return self._delete()
